// Copyright 2022 The Molego Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package utils

import (
	"crypto/sha256"
	"fmt"
	"io"
	"math/rand"
	"os"
	"strings"
	"time"
)

var r = rand.New(rand.NewSource(time.Now().UnixNano()))

// 字符串拼接
// capacity *int 默认目标字符串的容量
// strs *[]string 待拼接的字符串数组
func StringBuilder(capacity *int, strs *[]string) string {
	var builder strings.Builder
	builder.Grow(*capacity)
	for _, str := range *strs {
		builder.WriteString(str)
	}
	return builder.String()
}

// 字符串拼接
// builder *strings.Builder
// strs []string 待拼接的字符串数组
func StringAppender(builder *strings.Builder, strs ...string) {
	for _, str := range strs {
		builder.WriteString(str)
	}
}

// 获取一个指定范围的随机整数
// start int 起始边界
// end int 截止边界
func RandomInt(start int, end int) int {
	// rand.Seed(time.Now().UnixNano())
	random := r.Intn(end - start)
	random = start + random
	return random
}

// 生成指定长度的随机大写字符串
// len int 指定长度
// return string
func RandomStringUppercase(len int) string {
	bytes := make([]byte, len)
	for i := 0; i < len; i++ {
		b := r.Intn(26) + 65
		bytes[i] = byte(b)
	}
	return string(bytes)
}

// 生成指定长度的随机小写字符串
// len int 指定长度
// return string
func RandomStringLowercase(len int) string {
	bytes := make([]byte, len)
	for i := 0; i < len; i++ {
		b := r.Intn(26) + 97
		bytes[i] = byte(b)
	}
	return string(bytes)
}

// 计算指定文本的sha256摘要值
// text *string 待计算的文本指针
func Sha256(text *string) string {
	sum := sha256.Sum256([]byte(*text))
	return fmt.Sprintf("%x", sum)
}

// 计算指定文件的sha256摘要值
// path *string 待计算的文件路径指针
func Sha256File(path *string) (string, error) {
	// 对文件加密
	f, err := os.Open(*path)
	if err != nil {
		return "", err
	}

	defer f.Close()

	h := sha256.New()
	if _, err := io.Copy(h, f); err != nil {
		return "", err
	}

	// fmt.Printf("%x\n", h.Sum(nil))

	// sum := sha256.Sum256([]byte(*text))
	return fmt.Sprintf("%x", h.Sum(nil)), nil
}
